package com.nxcy.com.nxcy.servlet;


import com.google.gson.Gson;
import com.mongodb.client.*;
import org.bson.Document;
import org.bson.conversions.Bson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@WebServlet(urlPatterns = {"/major/list.do"})
public class MajorListServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
        MongoClient client = MongoClients.create(url);
        MongoIterable<String> names = client.listDatabaseNames();
        MongoDatabase g08 = client.getDatabase("g08");
        MongoCollection<Document> collection = g08.getCollection("student");
        List<Bson> queryList = new LinkedList<>();
        Document group = new Document().append("$group", new Document("_id", "$major"));
        queryList.add(group);
        AggregateIterable<Document> list = collection.aggregate(queryList);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        List<Document> majors = new ArrayList<>();
        for (Document d : list) {
            majors.add(new Document().append("code", d.get("_id")).append("name", d.get("_id")));
        }
        Gson gson = new Gson();
        response.getWriter().write(gson.toJson(majors));
    }
}
